import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';

class FramesAnimation extends StatefulWidget {
  final int initIndex; //当前帧动画索引
  final List images;

  FramesAnimation(
      {Key? key, //记录父组件状态
      this.initIndex = 0,
      required this.images})
      : super(key: key);

  @override
  FramesAnimationState createState() => FramesAnimationState();
}

class FramesAnimationState extends State<FramesAnimation>
    with SingleTickerProviderStateMixin {
  // //1.创建动画控制器和动画对象
  late AnimationController _animationController;
  late Animation _animation;

  @override
  void initState() {
    _animationController = AnimationController(
        vsync: this, duration: const Duration(milliseconds: 800));
    _animation = Tween(begin: 0.0, end: (widget.images.length - 1).toDouble())
        .animate(_animationController);

    //2.监听动画刷新；Flutter动画每一秒钟刷新60帧左右
    _animationController.addListener(() {
      //如果监听到动画刷新，就刷新当前组件
      setState(() {});
    });

    //默认启动动画
    if (widget.initIndex == 0) {
      startAnimation();
    }
    super.initState();
  }

  @override
  void dispose() {
    //3.释放动画资源
    _animationController.dispose();
    super.dispose();
  }

  //启动动画
  void startAnimation() => _animationController.forward();

  //重置动画
  void resetAnimation() => _animationController.reset();

  @override
  Widget build(BuildContext context) {
    int _frameIndex = _animation.value.floor();
    return Container(
      child: widget.images[_frameIndex],
    );
  }
}
